<template>
  <div class="cdd-form">
    <div class="cdd-title">
      <svg-icon icon-class="chart-pie-rounded" />
      <span>指标探源设置</span>
    </div>
    <design-form ref="form" />
  </div>
</template>
<script>
import request from '@/utils/request'
import DesignForm from './form.vue'
import { requestMatrixOriginSave } from '@/api/chart/origin'
import { getNewView } from './view-utils'

export default {
  name: 'ChartDesignEdit',
  components: { DesignForm },
  props: {
    panel: { type: Object, default: () => ({}) },
    chartType: { type: String, default: 'line' },
  },
  methods: {
    validate(callback) {
      return this.$refs.form.validate(callback)
    },
    /* 保存配置信息 */
    saveConfig() {
      const form = this.$refs.form.getValue()
      this.handleSaveConfig(form.config)
    },
    /* 保存新的视图 */
    async submit() {
      const form = this.$refs.form.getValue()
      const params = {
        name: this.panel.name,
        type: this.chartType,
        panelId: this.$route.query.panelId,
        tableId: form.tableId,
        xaxis: form.xaxis,
        yaxis: form.yaxis,
        filters: form.filters,
      }
      console.log('saveView params=', params)
      const view = getNewView(params)
      try {
        await this.handleSaveConfig(form.config)
        const { success, data } = await request({
          url: '/chart/view/newOne/' + params.panelId,
          method: 'post',
          loading: false,
          data: view,
        })
        if (success) {
          return { id: data.id, type: data.type }
        }
      } catch (error) {
        console.log('saveView error=', error)
      }

      this.$message.error('保存失败，请稍后重试')
      return { id: undefined, type: undefined }
    },
    async handleSaveConfig(config) {
      try {
        let { success, message } = await requestMatrixOriginSave({
          ...config,
          chartType: this.chartType || 'line',
          matrixId: this.$route.query.id,
        })
        if (!success) {
          throw new Error(message)
        }
      } catch (error) {
        throw new Error(error)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.cdd-form {
  .cdd-title {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .svg-icon {
      font-size: 28px;
      margin-right: 8px;
    }
    span {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  ::v-deep .avue-form {
    .avue-group__title {
      height: 20px;
      line-height: 20px;
      font-weight: 700;
      padding-left: 12px;
      // border-left: 4px solid var(--primary-color);
    }

    .el-form-item__label {
      font-weight: normal;
    }
  }
}
</style>
